import { createStore } from 'vuex'
import axios from 'axios'
import * as api from '@/api/auth'

export default createStore({
  state: {
    user: JSON.parse(localStorage.getItem('user')) || {},
    loading: false
  },
  getters: {
    isAuthenticated: state => !!state.user.username,
    currentUser: state => state.user
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_LOADING(state, status) {
      state.loading = status
    },
    LOGOUT(state) {
      state.user = {}
    }
  },
  actions: {
    // 登录 - 简化版，不使用JWT
    async login({ commit, dispatch }, credentials) {
      try {
        commit('SET_LOADING', true)
        
        console.log('登录凭据:', credentials);
        
        // 直接使用API服务
        const response = await api.login({
          username: credentials.username,
          password: credentials.password,
          rememberMe: !!credentials.rememberMe
        })
        
        console.log('登录响应:', response.data)
        
        // 从响应中获取用户信息
        if (response.data && response.data.code === 200 && response.data.data) {
          const user = response.data.data
          console.log('登录成功，用户信息:', user)
          
          // 将用户信息保存到本地存储和状态中
          localStorage.setItem('user', JSON.stringify(user))
          commit('SET_USER', user)
        } else {
          console.error('登录响应格式不正确:', response.data)
          return Promise.reject(new Error('登录响应中未包含用户信息或响应格式错误'))
        }
        
        commit('SET_LOADING', false)
        return Promise.resolve(response.data)
      } catch (error) {
        console.error('登录请求失败:', error)
        console.error('错误详情:', error.response ? error.response.data : '无响应数据')
        commit('SET_LOADING', false)
        return Promise.reject(error)
      }
    },
    
    // 注册
    async register({ commit }, registerData) {
      try {
        commit('SET_LOADING', true)
        const response = await axios.post('/auth/register', registerData)
        commit('SET_LOADING', false)
        return Promise.resolve(response.data)
      } catch (error) {
        commit('SET_LOADING', false)
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async fetchUserInfo({ commit }) {
      try {
        console.log('开始获取用户信息...')
        const response = await axios.get('/user/info')
        console.log('用户信息响应:', response.data)
        
        if (response.data && response.data.code === 200 && response.data.data) {
          const userInfo = response.data.data
          console.log('用户信息:', userInfo)
          
          localStorage.setItem('user', JSON.stringify(userInfo))
          commit('SET_USER', userInfo)
          return Promise.resolve(userInfo)
        } else {
          console.error('获取用户信息响应格式不正确:', response.data)
          return Promise.reject(new Error('获取用户信息响应格式错误'))
        }
      } catch (error) {
        console.error('获取用户信息请求失败:', error)
        return Promise.reject(error)
      }
    },
    
    // 登出 - 简化版
    logout({ commit }) {
      localStorage.removeItem('user')
      commit('LOGOUT')
      console.log('用户已登出')
    },
    
    // 重置用户信息 - 简化版
    resetUser({ commit }) {
      localStorage.removeItem('user')
      commit('LOGOUT')
      console.log('用户信息已重置')
    }
  }
}) 
 